<?php

namespace addons\facrm\controller\facrm\customer;

use addons\facrm\library\BackendApi;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * 联系人
 */
class Contacts extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'customer_id,name,mobile,telephone';
    protected $childrenAdminIds = [];
    protected $addon_config = array();

    public function _initialize()
    {
        parent::_initialize();
        $this->addon_config = get_addon_config('facrm');
        $this->model = model('\app\admin\model\facrm\customer\Contacts');
        $this->request->filter(['strip_tags']);
    }

    /**
     * 联系人列表
     */
    public function index()
    {
        $customer_id = $this->request->post("customer_id");

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $scene = model('\app\admin\model\facrm\Scene');
        $scene_list = $scene->where('types', 'contacts')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');

        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter_w['owner_user_id'] = $this->auth->id;
        $filter['scene_id']=isset($filter['scene_id'])?$filter['scene_id']:4;
        if (isset($filter['scene_id'])) {
            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限"));
            }
            switch ($filter['scene_id']) {
                case 4:
                    //全部 超级管理员不做限制
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                    $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                    break;
                case 5:
                    //我的
                    $filter_w['owner_user_id'] = $this->auth->id;
                    break;
                case 6:
                    //下属
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                    $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                    break;
                default://其它的还做TODO
                    $filter_w['owner_user_id'] = $this->auth->id;

            }

            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }
        if ($customer_id) {
            $filter_w['customer_id'] = $customer_id;
            //判断是否有该客户的权限
        }
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            $this->request->request(['custom' => $filter_w]);
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'owner_user' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'customer' => function ($customer) {
                    $customer->field('id,name');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        if ($this->addon_config['show_contacts'] != 1) {
            $pattern = '/(\d{3})(\d{4})(\d{4})/i';
            $replacement = '$1****$3';
            //为了安全隐藏手机和电话
            foreach ($list as $row) {
                $row->mobile =$row->mobile?preg_replace ($pattern,$replacement,$row->mobile ):'';
                $row->telephone =$row->telephone?preg_replace ($pattern,$replacement,$row->telephone ):'';
            }
        }
        $result = array("scene" => $scene_list, "rows" => $list);
        $this->success('', $result);
    }

    /**
     * 添加联系人
     * @return mixed
     */
    public function add()
    {

        $customer_id = $this->request->post("customer_id");
        if (!$customer_id)
            $this->error(__("请选择客户"));

        $customer = model('\app\admin\model\facrm\Customer');
        $row = $customer->get($customer_id);

        if (!$row)
            $this->error(__('客户不存在'));

        if (!$this->auth->checkCustomerAuth($customer_id, $this->auth)) {
            $this->error(__('您没有权限'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post();

            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $params=array_merge($params, [
                        'create_user_id' => $this->auth->id,
                        'owner_user_id' => $row->owner_user_id,
                        'customer_id' => $row->id,
                        'birthday' => !empty($params['birthday']) ? $params['birthday'] : NULL,
                    ]);
                    $result = $this->model->add($params);
                    Db::commit();
                } catch (ValidateException $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($this->model->getError()?__($this->model->getError()):__('添加失败'));
                }
            }

        }
        $this->error(__('No rows were inserted'));

    }

    /**
     * 修改联系人
     * @param null $ids
     * @ApiMethod (POST|GET)
     * @ApiParams(name="id", type="int", required=true, description="联系人ID")
     * @ApiBody ("get是获取，post是修改，修改的内容参数参考电脑版")
     */
    public function edit()
    {
        $id = $this->request->request('id', '', 'intval');
        if (!$id) {
            $this->error(__('No Results were found'));
        }

        $row = $this->model->get($id,['customer'=>function($qurey){
            $qurey->field('id,name');
        }]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (!$this->auth->checkCustomerAuth($row->customer_id, $this->auth)) {
            $this->error(__('您没有权限'));
        }
        if ($this->request->isPost()){
            $params = $this->request->post();
            $params['next_time'] = (isset($params['next_time'])&&$params['next_time']) ? strtotime($params['next_time']) : '0';

            if ($params) {
                $params = array_merge($params, [
                    'birthday' => !empty($params['birthday']) ? $params['birthday'] : NULL,
                ]);
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->edit($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($row->getError() ? __($row->getError()) : __('修改失败'));
                }
            }

            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->success("",$row);

    }

    /**
     * 删除联系人
     * @ApiMethod (POST)
     * @param string $ids
     */
    public function del()
    {

        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }

        $ids = $this->request->post("ids");
        if ($ids) {

            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }

            if (!$this->auth->checkCustomerAuth($row->customer_id, $this->auth)) {
                $this->error(__('您没有权限'));
            }
            $count = 0;
            Db::startTrans();
            try {

                $count = $row->delete();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success(__("删除成功"));
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
